import SwiftUI

// MARK: - 目标视图位置捕获
struct FramePreferenceKey: PreferenceKey {
    static var defaultValue: CGRect = .zero
    static func reduce(value: inout CGRect, nextValue: () -> CGRect) {
        value = nextValue()
    }
}

// MARK: - 顶部箭头气泡形状
struct TopArrowBubbleShape: Shape {
    var arrowPosition: CGFloat  // 箭头水平中心位置
    let arrowHeight: CGFloat = 10
    
    func path(in rect: CGRect) -> Path {
        Path { path in
            // 主体圆角矩形（留出顶部箭头空间）
            let bodyRect = CGRect(
                x: 0,
                y: arrowHeight,
                width: rect.width,
                height: rect.height - arrowHeight
            )
            path.addRoundedRect(in: bodyRect, cornerSize: CGSize(width: 8, height: 8))
            
            // 顶部箭头
            let arrowX = min(max(arrowPosition, arrowHeight), rect.width - arrowHeight)
            // 修改起始点到顶部
            path.move(to: CGPoint(x: arrowX, y: 0))
            // 修改线条到下方的左侧点
            path.addLine(to: CGPoint(x: arrowX - arrowHeight, y: arrowHeight))
            // 修改线条到下方的右侧点
            path.addLine(to: CGPoint(x: arrowX + arrowHeight, y: arrowHeight))
            path.closeSubpath()
        }
    }
}

// MARK: - 提示视图
struct TooltipView<Content: View>: View {
    let targetFrame: CGRect
    let content: Content
    @Binding var isPresented: Bool
    
    var body: some View {
        ZStack {
            // 全屏半透明点击层
            Color.black.opacity(0.001)
                .ignoresSafeArea()
                .contentShape(Rectangle())
//                .onTapGesture { isPresented = false }
                
            
            // 气泡内容
            GeometryReader { proxy in
                let globalFrame = proxy.frame(in: .global)
                let arrowX = targetFrame.midX - globalFrame.minX
                let arrowHeight = TopArrowBubbleShape(arrowPosition: arrowX).arrowHeight
                
                content
                    .padding(.horizontal, 12)
                    .padding(.top, arrowHeight + 12)
                    .padding(.bottom, 12)
                    .background(
                        TopArrowBubbleShape(arrowPosition: arrowX)
                            .fill(Color.black.opacity(0.9))
                            .shadow(color: .black.opacity(0.2), radius: 8, x: 0, y: 4)
                    )
                    .padding(.top, 5)//间距
                    .foregroundColor(.white)
                    .fixedSize()
                    .offset(
                        x: targetFrame.midX - globalFrame.midX,
                        y: targetFrame.maxY - globalFrame.minY
                    )
//                    .contentShape(Rectangle())
//                        .onTapGesture { isPresented = false }
            }
        }

    }
}

// MARK: - 视图扩展
extension View {
    func tooltip<Content: View>(
        isPresented: Binding<Bool>,
        @ViewBuilder content: @escaping () -> Content
    ) -> some View {
        self.background(
            GeometryReader { geo in
                Color.clear
                    .preference(
                        key: FramePreferenceKey.self,
                        value: isPresented.wrappedValue ? geo.frame(in: .global) : .zero
                    )
            }
        )
        .overlayPreferenceValue(FramePreferenceKey.self) { frame in
            if isPresented.wrappedValue {
                TooltipView(
                    targetFrame: frame,
                    content: content(),
                    isPresented: isPresented
                )
            }
        }
    }
}

// MARK: - 使用示例
// struct ContentView: View {
//    @State private var showTooltip = false
//
//    var body: some View {
//        VStack {
//            Button("显示功能说明") {
//                showTooltip.toggle()
//            }
//            .padding()
//            .background(Color.blue)
//            .foregroundColor(.white)
//            .cornerRadius(8)
//            .tooltip(isPresented: $showTooltip) {
//                Text("这是一个重要的操作按钮\n点击后会执行特定功能")
//                    .font(.system(size: 14))
//                    .multilineTextAlignment(.center)
//                    .fixedSize(horizontal: false, vertical: true)
//                    .frame(maxWidth: 200)
//            }
//
//            Spacer()
//        }
//        .padding()
//    }
// }

// MARK: - 预览
// #Preview {
//    ContentView()
// }
